﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Xml;


namespace NetworkUtils
{
    public enum MsgType
    {
        Info = 0,
        Beat = 1, //心跳包
        Data = 2
    };


    public class ProtocolObj
    {
        public int len { get; set; }
        public MsgType type { get; set; }
        public ProtocolObj(int len, MsgType type)
        {
            this.len = len;
            this.type = type;
        }
    }

    public static class ProtocolHelper
    {
        const string pattern = "(^<protocol>.*?</protocol>)";

        static public ProtocolObj GetProtocolObj(string ptcStr)
        {
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(ptcStr);
            var root = doc.DocumentElement.SelectSingleNode("MSG");
            int len = int.Parse(root.Attributes["len"].Value);
            MsgType type = (MsgType)int.Parse(root.Attributes["type"].Value);
            return new ProtocolObj(len, type);
        }


        static public string GetProtocolStr(string msg)
        {
            if (Regex.IsMatch(msg, pattern))
            {
                // 获取匹配的值
                string match = Regex.Match(msg, pattern).Groups[0].Value;
                return match;
            }
            throw new Exception("msg not match patter");
        }

        public static bool IsMacth(string msg)
        {
            return Regex.IsMatch(msg, pattern);
        }

        
        public static string ToString(ProtocolObj ptcObj)
        {
            string ptc = String.Format("<protocol><MSG type=\"{0}\" len=\"{1}\"/></protocol>", (int)ptcObj.type, ptcObj.len);
            return ptc;
        }
    }
}
